<template>
  <!-- 登录 -->
  <div>
    <h1>萤火商城</h1>
    <van-row type="flex" justify="center">
      <van-col span="20">
        <van-form @submit="login">
          <van-field
            v-model="username"
            name="用户名"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <p class="reg" @click="goreg">没有账号,请点击注册</p>
          <!-- 按钮 -->
          <van-button color="#ff6700" block>登录</van-button>
        </van-form>
      </van-col>
    </van-row>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    goreg() {
      this.$router.push({
        path: "/register",
      });
    },
    login() {
      // 根据用户名判断存在
      this.$axios
        .get("/users?username=" + this.username)
        .then((res) => {
          if (this.username != 0 && this.password != 0) {
            if (res.data.length == 0) {
              this.$dialog({ message: "没有该用户,请检查输入的用户名" });
            } else {
              let username = res.data[0].username;
              let id = res.data[0].id;
              sessionStorage.setItem("username", username);
              sessionStorage.setItem("id", id);
              if (res.data[0].password != this.password) {
                this.$dialog({ message: "输入密码有误,请检查!" });
                this.password = "";
              } else {
                this.$router.push("/home");
              }
            }
          } else {
            this.$dialog({ message: "用户名或密码不能为空!" });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style  scoped>
/* 标题 */
h1 {
  text-align: center;
  font-size: 50px;
  color: #ff6700;
  margin-top: 150px;
}
/* 提示 */
.reg {
  text-align: center;
  color: #ff6700;
}
/* 背景色 */
body {
  background: black !important;
}
</style>